package com.jzo2o.foundations.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.foundations.dto.response.ServeAggregationResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.mapper.*;
import com.jzo2o.foundations.model.domain.*;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.*;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 区域管理
 *
 * @author itcast
 * @create 2023/7/17 16:50
 **/
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Autowired
    private ServeItemMapper serveItemMapper;
    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private ServeTypeMapper serveTypeMapper;

    @Autowired
    private ServeSyncMapper serveSyncMapper;
    @Autowired
    private RestHighLevelClient client;

    @Override
    public ServeAggregationResDTO findServeDetailById(Long id) {
        return baseMapper.findServeDetailById(id);
    }

    /**
     * 查询全部服务
     *
     * @param regionId
     * @return
     */
    @Override
    public List<ServeAggregationTypeSimpleResDTO> serveTypeList(Long regionId) {
        //校验区域数据
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region) || region.getActiveStatus() !=2){
            return List.of();
        }

        //2、查询服务类型列表
        return  baseMapper.findServeTypeListByRegionId(regionId);
    }

    /**
     * 服务搜索
     *
     * @param cityCode
     * @param keyword
     * @param serveTypeId
     * @return
     */
    @Override
    public List<ServeSimpleResDTO> search(String cityCode, String keyword, Long serveTypeId) {
        //1. 创建请求对象
        SearchRequest request = new SearchRequest("serve_aggregation");

        //2. 封装请求参数
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //城市编码
        boolQuery.must(QueryBuilders.termQuery("city_code", cityCode));
        //服务类型id
        if (serveTypeId != null) {
            boolQuery.must(QueryBuilders.termQuery("serve_type_id", serveTypeId));
        }
        //关键词
        if (StrUtil.isNotEmpty(keyword)) {
            boolQuery.must(QueryBuilders.multiMatchQuery(keyword, "serve_item_name", "serve_type_name"));
        }
        request.source().query(boolQuery);//查询
        request.source().sort("serve_item_sort_num", SortOrder.ASC);//排序

        //3. 执行请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //4. 处理返回结果   List<ServeSimpleResDTO>
        if (response.getHits().getTotalHits().value == 0) {
            return List.of();
        }
        return Arrays.stream(response.getHits().getHits())
                .map(e -> JSONUtil.toBean(e.getSourceAsString(), ServeSimpleResDTO.class))
                .collect(Collectors.toList());
    }

    /**
     * 查询服务详情
     *
     * @param id
     * @return
     */
    @Override
    public ServeAggregationSimpleResDTO findById(Long id) {
        //1、查询服务表
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)||  serve.getSaleStatus() !=2){
            throw new ForbiddenOperationException("服务不存在或未启用");
        }
        //2. 查询服务项表

        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (ObjectUtil.isNull(serveItem)|| serveItem.getActiveStatus()!=2){
            throw new ForbiddenOperationException("服务项不存在或未启用");
        }

        //3、组装返回值
        ServeAggregationSimpleResDTO serveAggregationSimpleResDTO = BeanUtil.copyProperties(serve, ServeAggregationSimpleResDTO.class);
        BeanUtil.copyProperties(serveItem,serveAggregationSimpleResDTO);

        //处理映射不上的字段
        serveAggregationSimpleResDTO.setServeItemName(serveItem.getName());
        serveAggregationSimpleResDTO.setServeItemImg(serveItem.getImg());

        return serveAggregationSimpleResDTO;
    }
    /**
     * 查询热门服务列表
     *
     * @param regionId
     * @return
     */
    @Override
    @Caching(
            cacheable = {
                    // 没有查询到数据时缓存30分钟
                    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE,key = "#regionId"
                    ,unless = "#result.size()>0",cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),
                    //查询到数据时缓存永久
                    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE,key = "#regionId"
                    ,unless = "#result.size()==0",cacheManager = RedisConstants.CacheManager.FOREVER)
            }
    )
    public List<ServeAggregationSimpleResDTO> hotServeList(Long regionId) {
        //校验区域数据
        Region region = regionMapper.selectById(regionId);
        if (ObjectUtil.isNull(region) || region.getActiveStatus() !=2 ){
            return List.of();
        }

        //2. 查询热门服务列表
        return baseMapper.findServeListByRegionId(regionId);
    }
    /**
     * 查询首页服务列表
     *
     * @param regionId
     * @return
     *
     * JZ_CACHE:SERVE_ICON::区域id
     */
    @Override
    @Caching(
            cacheable={
                    // 没有查询到数据时缓存30分钟
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON,key = "#regionId"
                    ,unless = "#result.size()>0",cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES),
                    //查询到数据时缓存永久
                    @Cacheable(value = RedisConstants.CacheName.SERVE_ICON,key = "#regionId"
                    ,unless = "#result.size()==0",cacheManager = RedisConstants.CacheManager.FOREVER)
    })
    public List<ServeCategoryResDTO> firstPageServeList(Long regionId) {
        //1、校验区域是否存在 和 状态是否启用
        Region region = regionMapper.selectById(regionId);
        if(ObjectUtil.isNull(region) || region.getActiveStatus() !=2){
            throw new RuntimeException("区域不存在或未启用");
        }
        //2、查询服务列表
        List<ServeCategoryResDTO> list = baseMapper.findListByRegionId(regionId);

        if (CollectionUtil.isEmpty(list)){
            return List.of();
        }
        //截取
        list=CollectionUtil.sub(list,0,Math.min(list.size(),2));
//        list=list.subList(0,Math.min(list.size(),2));

        list.stream().forEach(e->{
            List<ServeSimpleResDTO> resDTOList = e.getServeResDTOList();
            CollectionUtil.sub(resDTOList,0,Math.min(resDTOList.size(),4));
//            resDTOList = resDTOList.subList(0,Math.min(resDTOList.size(),4));
            e.setServeResDTOList(resDTOList);
        });

        return list;
    }

    /**
     * 取消热门
     *
     * @param id
     */
    @Override
    public void offHot(Long id) {
        //区域服务当前热门状态
        //取消热门的前提是当前服务为热门
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve) || serve.getIsHot() ==0 ){
            throw new RuntimeException("区域服务不存在或非热门");
        }
        //更新状态
        serve.setIsHot(0);
        baseMapper.updateById(serve);
    }

    /**
     * 设置热门
     *
     * @param id
     */
    @Override
    public void onHot(Long id) {
        //区域服务当前非热门状态
        //设置热门的前提是当前服务为非热门
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve) || serve.getIsHot() ==1 ){
            throw new RuntimeException("区域服务不存在或已设置热门");
        }
        serve.setIsHot(1);
        //设置热门时间戳
        serve.setHotTimeStamp(System.currentTimeMillis());
        //更新状态
        baseMapper.updateById(serve);
    }
    /**
     * 区域服务下架
     *
     * @param id
     */
    @Override
    public void offSale(Long id) {
        //区域服务当前上架状态
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve) || serve.getSaleStatus() !=2 ){
            throw new RuntimeException("区域服务不存在或已下架");
        }
        serve.setSaleStatus(1);
        baseMapper.updateById(serve);
        //删除同步表数据
        serveSyncMapper.deleteById(id);
    }

    /**
     * 区域服务上架
     *
     * @param id
     */
    @Override
    public void onSale(Long id) {
        //1) 区域服务当前非上架状态
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve) || serve.getSaleStatus() ==2 ){
            throw new RuntimeException("区域服务不存在或已下架");
        }
        //2) 服务项目是启用状态
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if(ObjectUtil.isNull(serveItem)|| serveItem.getActiveStatus()!=2){
            throw new RuntimeException("服务项未启用");
        }
        //3) 更新服务状态
        serve.setSaleStatus(2);
        baseMapper.updateById(serve);

        //4) 添加同步表数据
        addServeSync(id);
    }
    /**
     * 新增服务同步数据
     *
     * @param serveId 服务id
     */
    private void addServeSync(Long serveId) {
        //服务信息
        Serve serve = baseMapper.selectById(serveId);
        //区域信息
        Region region = regionMapper.selectById(serve.getRegionId());
        //服务项信息
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        //服务类型
        ServeType serveType = serveTypeMapper.selectById(serveItem.getServeTypeId());

        ServeSync serveSync = new ServeSync();
        serveSync.setServeTypeId(serveType.getId());
        serveSync.setServeTypeName(serveType.getName());
        serveSync.setServeTypeIcon(serveType.getServeTypeIcon());
        serveSync.setServeTypeImg(serveType.getImg());
        serveSync.setServeTypeSortNum(serveType.getSortNum());

        serveSync.setServeItemId(serveItem.getId());
        serveSync.setServeItemIcon(serveItem.getServeItemIcon());
        serveSync.setServeItemName(serveItem.getName());
        serveSync.setServeItemImg(serveItem.getImg());
        serveSync.setServeItemSortNum(serveItem.getSortNum());
        serveSync.setUnit(serveItem.getUnit());
        serveSync.setDetailImg(serveItem.getDetailImg());
        serveSync.setPrice(serve.getPrice());

        serveSync.setCityCode(region.getCityCode());
        serveSync.setId(serve.getId());
        serveSync.setIsHot(serve.getIsHot());
        serveSyncMapper.insert(serveSync);
    }

    /**
     * 区域服务新增
     *
     * @param dtoList
     */
    //事务控制
    //TODO 优化for 循环
    @Transactional
    @Override
    public void add(List<ServeUpsertReqDTO> dtoList) {
        for (ServeUpsertReqDTO dto : dtoList) {
            //1. 服务项目必须是启用状态的才能添加到区域
            ServeItem serveItem = serveItemMapper.selectById(dto.getServeItemId());
            if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != 2){
                throw new RuntimeException("服务项不存在或未启用");
            }
            //2. 一个服务项目对于一个区域，只能添加一次
            //根据区域id和服务项目id（两者同时存在）  查询服务表中是否有数据
            Integer i = baseMapper.selectCount(new LambdaQueryWrapper<Serve>()
                    .eq(Serve::getServeItemId, dto.getServeItemId())
                    .eq(Serve::getRegionId, dto.getRegionId())
            );
            if (i>0){
                throw new RuntimeException("该服务项已经添加到该区域");
            }

            //3. 新增
            Serve serve = BeanUtil.copyProperties(dto, Serve.class);
            //补全城市编码字段
            Region region = regionMapper.selectById(dto.getRegionId());
            if (ObjectUtil.isNull(region)){
                throw new RuntimeException("区域不存在");
            }
            serve.setCityCode(region.getCityCode());
            baseMapper.insert(serve);
        }
    }
    /**
     * 区域服务分页查询
     *
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> fingByPage(ServePageQueryReqDTO servePageQueryReqDTO) {
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryList(servePageQueryReqDTO.getRegionId()));
    }

    /**
     * 区域服务删除
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        baseMapper.deleteById(id);
    }


}
